//
//  ImageUtil.m
//  ImageEffect
//
//  Created by lichq on 13-12-23.
//  Copyright (c) 2013√ÇœÄ¬• lichq. All rights reserved.
//

#import "ImageUtil.h"
#import "QFilterMethod.h"
#import "QLayerBlending.h"
#import "QTemplet.h"

@implementation ImageUtil




/*
//+ (UIImage*)imageFilter:(UIImage*)image Filter:(void)
//static void FilterImage(UIImage *image, void (*changePixelFun)(unsigned char **imagePixel, int w, int h))
//+ (UIImage *) FilterImage:(UIImage *)image void
static void FilterImage(UIImage *image, void (*changePixelFun)(unsigned char **imagePixel, int w, int h))
{
    unsigned char *imagePixel = RequestImagePixelData(image);   //√ä‚â•¬Æ√ä√ë√®√Å¬±¬™√Ç√ª√?
    
	CGImageRef imageRef = [image CGImage];
	GLuint w = CGImageGetWidth(imageRef);
	GLuint h = CGImageGetHeight(imageRef);
    
    changePixelFun(&imagePixel, w, h);
    
    UIImage *newImage = [self createNewImageByImagePixel:imagePixel width:w height:h];
    return newImage;
}
//*/


+ (UIImage*)imageLomoNTSC:(UIImage*)image
{
	unsigned char *imagePixel = RequestImagePixelData(image);   //√ä‚â•¬Æ√ä√ë√®√Å¬±¬™√Ç√ª√?
    
	CGImageRef imageRef = [image CGImage];
	GLuint w = CGImageGetWidth(imageRef);
	GLuint h = CGImageGetHeight(imageRef);
    
    changePixel_lomoNTSC(&imagePixel, w, h);
    
    UIImage *newImage = [QImage createNewImageByImagePixel:imagePixel width:w height:h];
    return newImage;
    
    /*
    int red, green, blue, alpha;           //√à√≥¬•√ä√©‚Ä¢√ã√∏√™√Å√Ü√≥√î¬∫√•√à√°√°√Å√Æ¬Æ√ä√•√°√à√≠√†√ä√π‚Ä¢√ä√ÆœÄ√Ç√®√≤√Ç√Ñ¬∫√î¬∫√•‚Ä∞Œ©√∫√Å√Æ¬Æ√ä√≤√òC√Ç√°Œ©√ä√Ø‚àû√Ç√∫¬Æ√Ç√®¬∂‚Ä∞‚àè√Ñ‚Ä∞‚àè‚Ñ¢√ä√±√°‚Ä∞¬™‚àÇ√à√°√•
    long startByte = 0;
    
    for(int y = 0;y< h;y++)
    {
        for (int x = 0; x<w; x++)
        {
            startByte = (y * w + x) * 4;
            
            red = imagePixel[startByte];
            green = imagePixel[startByte+1];
            blue = imagePixel[startByte+2];
            alpha = imagePixel[startByte+3];
            
            changeRGBA_lomoNTSC(&red, &green, &blue, &alpha);
            
            imagePixel[startByte] = red;
            imagePixel[startByte+1] = green;
            imagePixel[startByte+2] = blue;
            imagePixel[startByte+3] = alpha;
        }
     }
     
    
    //‚Ä∞‚àè√£√à√π¬¢√Å√∂√ë‚Ä∞¬™¬£√Å‚Ä†√Ö√Ç√†√µ√Ç¬™‚à´√ã¬∂√Ö√ã√¶√¨√Ç√°‚à´√Å√∂√ë√Ç√µ√¶√Ç√â√®√Å√∂√ë√Å√µ‚àè√Ç√ñ‚â•√Ç√®√á√ä√Ø‚àû
     NSInteger dataLength = w * h * 4;
     CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, imagePixel, dataLength, NULL);
     
     int bitsPerComponent = 8;
     int bitsPerPixel = 32;
     int bytesPerRow = 4 * w;
     CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
     CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault;
     CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;
     
     CGImageRef newImageRef = CGImageCreate(w, h, bitsPerComponent, bitsPerPixel, bytesPerRow,colorSpaceRef, bitmapInfo, provider, NULL, NO, renderingIntent);//√Ç√†√µ√Ç¬™‚à´√ã¬∂√Ö√ã√¶√¨√Ç√°‚à´√Å√∂√ë√Ç√µ√¶√Ç√â√®
     
     UIImage *newImage = [UIImage imageWithCGImage:newImageRef];
     
     CFRelease(newImageRef);
     CGColorSpaceRelease(colorSpaceRef);
     CGDataProviderRelease(provider);
     
     return newImage;
     */
}

+ (UIImage*)imageLomoMethod1:(UIImage*)image
{
	unsigned char *imagePixel = RequestImagePixelData(image);
    
	CGImageRef imageRef = [image CGImage];
	GLuint w = CGImageGetWidth(imageRef);
	GLuint h = CGImageGetHeight(imageRef);
    
    changePixel_lomoMethod1(&imagePixel, w, h);
    
    UIImage *newImage = [QImage createNewImageByImagePixel:imagePixel width:w height:h];
    return newImage;
}

+ (UIImage*)imageHeibai:(UIImage*)image
{
	unsigned char *imagePixel = RequestImagePixelData(image);
    
	CGImageRef imageRef = [image CGImage];
	GLuint w = CGImageGetWidth(imageRef);
	GLuint h = CGImageGetHeight(imageRef);
    
    changePixel_heibai(&imagePixel, w, h);
    
    UIImage *newImage = [QImage createNewImageByImagePixel:imagePixel width:w height:h];
    return newImage;
}

+ (UIImage*)imageHuaijiu:(UIImage*)image
{
	unsigned char *imagePixel = RequestImagePixelData(image);
    
	CGImageRef imageRef = [image CGImage];
	GLuint w = CGImageGetWidth(imageRef);
	GLuint h = CGImageGetHeight(imageRef);
    
    changePixel_huaijiu(&imagePixel, w, h);
    
    UIImage *newImage = [QImage createNewImageByImagePixel:imagePixel width:w height:h];
    return newImage;
}

+ (UIImage*)imageGete:(UIImage*)image
{
	unsigned char *imagePixel = RequestImagePixelData(image);
    
	CGImageRef imageRef = [image CGImage];
	GLuint w = CGImageGetWidth(imageRef);
	GLuint h = CGImageGetHeight(imageRef);
    
    changePixel_gete(&imagePixel, w, h);
    
    UIImage *newImage = [QImage createNewImageByImagePixel:imagePixel width:w height:h];
    return newImage;
}

+ (UIImage*)imageRuise:(UIImage*)image
{
	unsigned char *imagePixel = RequestImagePixelData(image);
    
	CGImageRef imageRef = [image CGImage];
	GLuint w = CGImageGetWidth(imageRef);
	GLuint h = CGImageGetHeight(imageRef);
    
    changePixel_ruise(&imagePixel, w, h);
    
    UIImage *newImage = [QImage createNewImageByImagePixel:imagePixel width:w height:h];
    return newImage;
}



+ (UIImage*)imageDanya:(UIImage*)image
{
	unsigned char *imagePixel = RequestImagePixelData(image);
    
	CGImageRef imageRef = [image CGImage];
	GLuint w = CGImageGetWidth(imageRef);
	GLuint h = CGImageGetHeight(imageRef);
    
    changePixel_danya(&imagePixel, w, h);
    
    UIImage *newImage = [QImage createNewImageByImagePixel:imagePixel width:w height:h];
    return newImage;
}

+ (UIImage*)imageJiuhong:(UIImage*)image
{
	unsigned char *imagePixel = RequestImagePixelData(image);
    
	CGImageRef imageRef = [image CGImage];
	GLuint w = CGImageGetWidth(imageRef);
	GLuint h = CGImageGetHeight(imageRef);
    
    changePixel_jiuhong(&imagePixel, w, h);
    
    UIImage *newImage = [QImage createNewImageByImagePixel:imagePixel width:w height:h];
    return newImage;
}

+ (UIImage*)imageQingning:(UIImage*)image
{
	unsigned char *imagePixel = RequestImagePixelData(image);
    
	CGImageRef imageRef = [image CGImage];
	GLuint w = CGImageGetWidth(imageRef);
	GLuint h = CGImageGetHeight(imageRef);
    
    changePixel_qingning(&imagePixel, w, h);
    
    UIImage *newImage = [QImage createNewImageByImagePixel:imagePixel width:w height:h];
    return newImage;
}

+ (UIImage*)imageLangman:(UIImage*)image
{
	unsigned char *imagePixel = RequestImagePixelData(image);
    
	CGImageRef imageRef = [image CGImage];
	GLuint w = CGImageGetWidth(imageRef);
	GLuint h = CGImageGetHeight(imageRef);
    
    changePixel_langman(&imagePixel, w, h);
    
    UIImage *newImage = [QImage createNewImageByImagePixel:imagePixel width:w height:h];
    return newImage;
}

+ (UIImage*)imageGuangyun:(UIImage*)image
{
	unsigned char *imagePixel = RequestImagePixelData(image);
    
	CGImageRef imageRef = [image CGImage];
	GLuint w = CGImageGetWidth(imageRef);
	GLuint h = CGImageGetHeight(imageRef);
    
    changePixel_guangyun(&imagePixel, w, h);
    
    UIImage *newImage = [QImage createNewImageByImagePixel:imagePixel width:w height:h];
    return newImage;
}


+ (UIImage*)imageLandiao:(UIImage*)image
{
	unsigned char *imagePixel = RequestImagePixelData(image);
    
	CGImageRef imageRef = [image CGImage];
	GLuint w = CGImageGetWidth(imageRef);
	GLuint h = CGImageGetHeight(imageRef);
    
    changePixel_landiao(&imagePixel, w, h);
    
    UIImage *newImage = [QImage createNewImageByImagePixel:imagePixel width:w height:h];
    return newImage;
}

+ (UIImage*)imageMenghuan:(UIImage*)image
{
	unsigned char *imagePixel = RequestImagePixelData(image);
    
	CGImageRef imageRef = [image CGImage];
	GLuint w = CGImageGetWidth(imageRef);
	GLuint h = CGImageGetHeight(imageRef);
    
    changePixel_menghuan(&imagePixel, w, h);
    
    UIImage *newImage = [QImage createNewImageByImagePixel:imagePixel width:w height:h];
    return newImage;
}

+ (UIImage*)imageYese:(UIImage*)image
{
	unsigned char *imagePixel = RequestImagePixelData(image);
    
	CGImageRef imageRef = [image CGImage];
	GLuint w = CGImageGetWidth(imageRef);
	GLuint h = CGImageGetHeight(imageRef);
    
    changePixel_yese(&imagePixel, w, h);
    
    UIImage *newImage = [QImage createNewImageByImagePixel:imagePixel width:w height:h];
    return newImage;
}

+ (UIImage*)imageLomoMethod3:(UIImage*)image
{
	unsigned char *imgPixel = RequestImagePixelData(image);
    
	CGImageRef imageRef = [image CGImage];
	GLuint w = CGImageGetWidth(imageRef);
	GLuint h = CGImageGetHeight(imageRef);
    
    changePixel_LomoMethod3(&imgPixel, w, h);
    
    UIImage *newImage = [QImage createNewImageByImagePixel:imgPixel width:w height:h];
    return newImage;
}

+ (UIImage *)imageSketch:(UIImage *)image{
    unsigned char *imgPixel = RequestImagePixelData(image);
    
	CGImageRef imageRef = [image CGImage];
	GLuint w = CGImageGetWidth(imageRef);
	GLuint h = CGImageGetHeight(imageRef);
    
    changePixel_Sketch(&imgPixel, w, h);
    
    UIImage *newImage = [QImage createNewImageByImagePixel:imgPixel width:w height:h];
    return newImage;
}

+ (UIImage*)imageScrap:(UIImage*)image //√Å¬¢√©√Å√¢√°
{
	unsigned char *imgPixel = RequestImagePixelData(image);
    
	CGImageRef imageRef = [image CGImage];
	GLuint w = CGImageGetWidth(imageRef);
	GLuint h = CGImageGetHeight(imageRef);
    
    changePixel_Scrap(&imgPixel, w, h);
    
    UIImage *newImage = [QImage createNewImageByImagePixel:imgPixel width:w height:h];
    return newImage;
}


+ (UIImage*)imageDipian:(UIImage*)image
{
	unsigned char *imgPixel = RequestImagePixelData(image);
	CGImageRef imageRef = [image CGImage];
	GLuint w = CGImageGetWidth(imageRef);
	GLuint h = CGImageGetHeight(imageRef);
    
    changePixel_Dipian(&imgPixel, w, h);
    
    UIImage *newImage = [QImage createNewImageByImagePixel:imgPixel width:w height:h];
    return newImage;
}

#define BITMAPFILEHEADERLENGTH  14
#define BM  19778
unsigned int OffSet = 0;
long width;
long height;
unsigned char r[2000][2000], output_r[2000][2000];
unsigned char g[2000][2000], output_g[2000][2000];
unsigned char b[2000][2000], output_b[2000][2000];



int dosomething(){
    //Open bmp file
    unsigned char *fp_temp;
    FILE *fpbmp;
    FILE *fpout;
    
    NSString *path = [[NSBundle mainBundle]pathForResource:@"bmp1" ofType:@"bmp"];
    const char *paths = [path UTF8String];
    fpbmp = fopen(paths, "rb");
    if (fpbmp == NULL) {
        printf("Open bmp failed!!!\n");
        return 1;
    }
    
    NSArray *pathout = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDir = [pathout objectAtIndex:0];
    NSString *path2 = [NSString stringWithFormat:@"%@/%@",docDir,@"bmp2.bmp"];
//    NSString *path2 = [[NSBundle mainBundle]pathForResource:@"bmp2" ofType:@"bmp"];
    const char *paths2 = [path2 UTF8String];
    fpout = fopen(paths2, "wb+");
//    fpout = fopen("out.bmp", "wb+");
    if (fpout == NULL) {
        printf("Open out.bmp failed!!!\n");
        return 1;
    }
    bmpFileTest(fpbmp);     //Test the file is bmp file ornot
    bmpHeaderPartLength(fpbmp);     //Get the length of Header Part
    BmpWidthHeight(fpbmp);  //Get the width and width of the Data Part
    //
    fseek(fpbmp,0L,SEEK_SET);
    fseek(fpout,0L,SEEK_SET);
    
    fp_temp = malloc(OffSet);
    fread(fp_temp,1,OffSet,fpbmp);
    fwrite(fp_temp,1,OffSet,fpout);
    bmpDataPart(fpbmp); //Reserve the data to file
    
    //如果你想对图片进行处理，请在这里插入函数
    
    bmpoutput(fpout);
    fclose(fpbmp);
    fclose(fpout);
    
    return 0;
}


void bmpoutput(FILE* fpout){
    int i,j=0;
    int stride;
    unsigned char *pixout = NULL;
    stride=(24*width+31)/8;
    stride=stride/4*4;
    pixout=malloc(stride);
    fseek(fpout,OffSet,SEEK_SET);
    for(j=0;j<height;j++){
        for(i=0;i<width;i++){
            pixout[i*3+2]=output_r[height-1-j][i];
            pixout[i*3+1]=output_g[height-1-j][i];
            pixout[i*3]=output_b[height-1-j][i];
        }
        
        fwrite(pixout,1,stride,fpout);
    }
}

void bmpDataPart(FILE*fpbmp){
    int i,j=0;
    int stride;
    unsigned char *pix = NULL;
    FILE *fpr;
    FILE *fpg;
    FILE *fpb;
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDir = [paths objectAtIndex:0];
    NSString *filePathR = [NSString  stringWithFormat:@"%@/bmpr.txt", docDir];
    NSString *filePathG = [NSString  stringWithFormat:@"%@/bmpg.txt", docDir];
    NSString *filePathB = [NSString  stringWithFormat:@"%@/bmpb.txt", docDir];
    if((fpr=fopen([filePathR UTF8String],"w+"))==NULL){
//    if((fpr=fopen("bmpr.txt","w+"))==NULL){
        printf("Failed to construct file bmpr.txt.!!!");
        exit(1);
    }
    
    if((fpg=fopen([filePathG UTF8String],"w+"))==NULL){
//    if((fpg=fopen("bmpg.txt","w+")) == NULL){
        printf("Failed to construct file bmpg.txt.!!!");
        exit(1);
    }
    
    if((fpb=fopen([filePathB UTF8String],"w+"))==NULL){
//    if((fpb=fopen("bmpb.txt","w+")) == NULL){
        printf("Failed to construct file bmpb.txt.!!!");
        exit(1);
    }
    
    fseek(fpbmp, OffSet, SEEK_SET);
    stride = (24*width+31)/8;
    stride = stride/4*4;
    pix = malloc(stride);
    
    for(j=0;j<height;j++){
        fread(pix,1,stride,fpbmp);
        for(i=0;i<width;i++){
            r[height-1-j][i] = pix[i*3+2];
            g[height-1-j][i] = pix[i*3+1];
            b[height-1-j][i] = pix[i*3];
            
            output_r[height-1-j][i] = pix[i*3+2];
            output_g[height-1-j][i] = pix[i*3+1];
            output_b[height-1-j][i] = pix[i*3];
        }
    }
    
    for(i=0;i<height;i++){
        for(j=0;j<width-1;j++){
            fprintf(fpb,"%4d",b[i][j]);
            fprintf(fpg,"%4d",g[i][j]);
            fprintf(fpr,"%4d",r[i][j]);
        }
        fprintf(fpb,"%4d\n",b[i][j]);
        fprintf(fpg,"%4d\n",g[i][j]);
        fprintf(fpr,"%4d\n",r[i][j]);
    }
    fclose(fpr);
    fclose(fpg);
    fclose(fpb);
}

void bmpFileTest(FILE *fpbmp){
    unsigned short bfType = 0;
    fseek(fpbmp,0L,SEEK_SET);   //seek_set起始位置
    fread(&bfType,sizeof(char),2,fpbmp);
    if(BM != bfType){
        printf("This file is not bmp file.!!!\n");
        exit(1);
    }
}

//To get the OffSet of header to data part
void bmpHeaderPartLength(FILE *fpbmp){
    fseek(fpbmp,10L,SEEK_SET);
    fread(&OffSet,sizeof(char),4,fpbmp);
    printf("The Header Part is of length %d.\n", OffSet);
}

//To get the width and height of the bmp file
void BmpWidthHeight(FILE*fpbmp){
    fseek(fpbmp,18L,SEEK_SET);
    fread(&width,sizeof(char),4,fpbmp);
    
    fseek(fpbmp,22L,SEEK_SET);
    fread(&height,sizeof(char),4,fpbmp);
    
    printf("The Width of the bmp file is %ld.\n",width);
    printf("The Height of the bmp file is %ld.\n",height);
}


+ (UIImage *)addText:(NSString *)string ToImage:(UIImage *)image{
    //get image width and height
    int w = image.size.width;
    int h = image.size.height;
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    //create a graphic context with CGBitmapContextCreate
    CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 4 * w, colorSpace, kCGImageAlphaPremultipliedFirst);
    CGContextDrawImage(context, CGRectMake(0, 0, w, h), image.CGImage);
    CGContextSetRGBFillColor(context, 0.0, 1.0, 1.0, 1);
    char* text = (char *)[string cStringUsingEncoding:NSASCIIStringEncoding];
    CGContextSelectFont(context, "Georgia", 30, kCGEncodingMacRoman);
    CGContextSetTextDrawingMode(context, kCGTextFill);
    CGContextSetRGBFillColor(context, 255, 0, 0, 1);
    CGContextSetTextMatrix(context, CGAffineTransformMakeRotation( -M_PI/4 ));
    //    CGContextShowTextAtPoint(context, 60, 390, text, strlen(text));
    CGContextShowTextAtPoint(context, 60, 160, text, strlen(text));
    //Create image ref from the context
    CGImageRef imageMasked = CGBitmapContextCreateImage(context);
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    return [UIImage imageWithCGImage:imageMasked];
}

bool isEqualInPixelIndex(unsigned char *imagePixel1, int pixelIndex1, unsigned char *imagePixel2, int pixelIndex2){
    int m1 = imagePixel1[pixelIndex1*4];
    int m2 = imagePixel1[pixelIndex1*4+1];
    int m3 = imagePixel1[pixelIndex1*4+2];
    
    int n1 = imagePixel2[pixelIndex2*4];
    int n2 = imagePixel2[pixelIndex2*4+1];
    int n3 = imagePixel2[pixelIndex2*4+2];
    if (m1 == n1 && m2 == n2 && m3 == n3) {
        return true;
    }else{
        return false;
    }
}

+ (UIImage*)imageToComposeWithImage1:(UIImage*)image1 Image2:(UIImage *)image2 ByImage:(UIImage *)imagemuban
{
    unsigned char *imgPixelmuban = RequestImagePixelData(imagemuban);
    
	CGImageRef inImageRefmuban = [imagemuban CGImage];
	int wmuban = CGImageGetWidth(inImageRefmuban); 
	int hmuban = CGImageGetHeight(inImageRefmuban);
    
//    int length = w * h * 4;
//    unsigned char *newImagePixel = (unsigned char *)calloc(length, sizeof(unsigned char));
//    int num[wmuban * hmuban] = {0};
    int num[100000] = {0};
    int count = 0;
    int xmin, xmax, ymin, ymax;
    bool first = true;
    
//    int  myQudian = (9*220+9);
//    int  myQudian = (150*220+9);
    int  myQudian = (150*220+220-9);
    for(int y = 0;y< hmuban;y++)
	{
		for (int x = 0; x < wmuban; x++)
		{
            int pixelIndex = y * wmuban + x;
            if (isEqualInPixelIndex(imgPixelmuban, pixelIndex, imgPixelmuban, myQudian)) {
                if (first) {
                    xmin = x;
                    ymin = y;
                    xmax = x;
                    ymax = y;
                    first = false;
                }else{
                    xmin = MIN(xmin, x);
                    xmax = MAX(xmax, x);
                    ymin = MIN(ymin, y);
                    ymax = MAX(ymax, y);
                }
                num[count++] = pixelIndex;
            }
        }
    }
    int qudian = imgPixelmuban[myQudian];
    NSLog(@"first = %d, count = %d",qudian, count);
    
    int newW = xmax - xmin;
    int newH = ymax - ymin;
    NSLog(@"newW = %d, newH = %d", newW, newH);
    
    image1 = [ImageUtil scaleImage:image1 ToWidth:newW Height:newH];
    unsigned char *imgPixel1 = RequestImagePixelData(image1);

    for (int i = 0; i < count; i++) {
        int startByte = num[i]*4;
        
        int y = num[i]/wmuban - ymin;
        int x = num[i]%wmuban - xmin;
        int startByte1 = (y * newW + x) * 4;
        
        imgPixelmuban[startByte] = imgPixel1[startByte1];
        imgPixelmuban[startByte+1] = imgPixel1[startByte1+1];
        imgPixelmuban[startByte+2] = imgPixel1[startByte1+2];

    }
    
//    int d = 8;
//    for (int y = d; y < hmuban-d; y++) {
//        for (int x = d; x < wmuban-d; x++) {
//            int i = (y*wmuban+x)*4;
//            if (y < (2*h*x)/(3*w) + h/3- d/2 && y < -(2*h*x)/(3*wmuban) + hmuban - d/2){
//                imgPixelmuban[i] = 0;
//                imgPixelmuban[i+1] = 110;
//                imgPixelmuban[i+2] = 0;
//                imgPixelmuban[i+3] = 1;
//            }else if ((6*y-2*h-3*d)*3*w > 6*(2*h*x) || (2*y-2*h-d)*3*w > -2*(2*h*x)){
//                if (x< w/2 - d/2) {
//                    imgPixelmuban[i] = 255;
//                    imgPixelmuban[i+1] = 0;
//                    imgPixelmuban[i+2] = 0;
//                    imgPixelmuban[i+3] = 1;
//                }else if(x >w/2 + d/2){
//                    imgPixelmuban[i] = 0;
//                    imgPixelmuban[i+1] = 0;
//                    imgPixelmuban[i+2] = 255;
//                    imgPixelmuban[i+3] = 1;
//                }
//            }
//        }
//    }
    
    
    UIImage *newImage = [QImage createNewImageByImagePixel:imgPixelmuban width:wmuban height:hmuban];
    return newImage;
}





    
+ (UIImage *)createMubanImage:(QTempletInfo)templetInfo{
    unsigned char *templetPixel = templetInfo.templetPixel;
    int w = templetInfo.templetW;
    int h = templetInfo.templetH;
//    QRegionInfo *regionInfo = templetInfo.regionInfo;
    
    UIImage *newImage = [QImage createNewImageByImagePixel:templetPixel width:w height:h];
    return newImage;
}


+(QTempletInfo)QFillImage:(UIImage *)image ToTempletInfo:(QTempletInfo)templetInfo InRegion:(int)region{
    QImagePixelInfo imagePixelInfo = [QImage getImagePixelInfoFromImage:image];
    
    
    templetInfo = QFillImageToTempletInRegion(imagePixelInfo, templetInfo, region); //region 要和 imagePixel配套
    /*
    unsigned char *templetPixel = templetInfo.templetPixel;
    int w = templetInfo.templetW;
    int h = templetInfo.templetH;
    QRegionInfo *regionInfo = templetInfo.regionInfo;
    
    unsigned char *imgPixel1 = imagePixelInfo.imagePixel;
    imgPixel1 = QScaleImagePixelFitRegion(imagePixelInfo, regionInfo, 0);
    unsigned char *imgPixel2 = QScaleImagePixelFitRegion(imagePixelInfo, regionInfo, 1);
    unsigned char *imgPixel3 = QScaleImagePixelFitRegion(imagePixelInfo, regionInfo, 2);
    
    int d = 8;
    for (int y = d; y < h-d; y++) {
        for (int x = d; x < w-d; x++) {
            int i = (y*w+x)*4;
            if (y < (2*h*x)/(3*w) + h/3- d/2 && y < -(2*h*x)/(3*w) + h - d/2){
                
                int regionIndex = 0;
                unsigned char *imgPixel = imgPixel1;
                
                int regionXMin = regionInfo[regionIndex].xmin;
                int regionXMax = regionInfo[regionIndex].xmax;
                int regionYMin = regionInfo[regionIndex].ymin;
                
                int newW = regionXMax - regionXMin;
                
                int y2 = y - regionYMin;
                int x2 = x - regionXMin;
                int i2 = (y2 * newW + x2)*4;
                
                
                templetPixel[i] = imgPixel[i2];
                templetPixel[i+1] = imgPixel[i2+1];
                templetPixel[i+2] = imgPixel[i2+2];
                templetPixel[i+3] = imgPixel[i2+3];

            }else if ((6*y-2*h-3*d)*3*w > 6*(2*h*x) || (2*y-2*h-d)*3*w > -2*(2*h*x)){
                if (x< w/2 - d/2) {
                    
                    int regionIndex = 1;
                    unsigned char *imgPixel = imgPixel2;
                    
                    int regionXMin = regionInfo[regionIndex].xmin;
                    int regionXMax = regionInfo[regionIndex].xmax;
                    int regionYMin = regionInfo[regionIndex].ymin;
                    
                    int newW = regionXMax - regionXMin;
                    
                    int y2 = y - regionYMin;
                    int x2 = x - regionXMin;
                    int i2 = (y2 * newW + x2)*4;
                    
                    templetPixel[i] = imgPixel[i2];
                    templetPixel[i+1] = imgPixel[i2+1];
                    templetPixel[i+2] = imgPixel[i2+2];
                    templetPixel[i+3] = imgPixel[i2+3];
                    
//                    templetPixel[i] = 255;
//                    templetPixel[i+1] = 0;
//                    templetPixel[i+2] = 0;
//                    templetPixel[i+3] = 1;
                }else if(x >w/2 + d/2){
                    int regionIndex = 2;
                    unsigned char *imgPixel = imgPixel3;
                    
                    int regionXMin = regionInfo[regionIndex].xmin;
                    int regionXMax = regionInfo[regionIndex].xmax;
                    int regionYMin = regionInfo[regionIndex].ymin;
                    
                    int newW = regionXMax - regionXMin;
                    
                    int y2 = y - regionYMin;
                    int x2 = x - regionXMin;
                    int i2 = (y2 * newW + x2)*4;
                    
                    templetPixel[i] = imgPixel[i2];
                    templetPixel[i+1] = imgPixel[i2+1];
                    templetPixel[i+2] = imgPixel[i2+2];
                    templetPixel[i+3] = imgPixel[i2+3];
                    
//                    templetPixel[i] = 0;
//                    templetPixel[i+1] = 0;
//                    templetPixel[i+2] = 255;
//                    templetPixel[i+3] = 1;
                }
            }
        }
    }
//    */
    return templetInfo;
//    UIImage *newImage = [QImage createNewImageByImagePixel:templetPixel width:w height:h];
//    return newImage;
    
}


+ (UIImage*)imageToComposeWithImage1:(UIImage*)image1 Image2:(UIImage *)image2
{
    
	unsigned char *imgPixel1 = RequestImagePixelData(image1);   //√ä‚â•¬Æ√ä√ë√®√Å¬±¬™√Ç√ª√?
	CGImageRef inImageRef1 = [image1 CGImage];
	GLuint w1 = CGImageGetWidth(inImageRef1);    //440
	GLuint h1 = CGImageGetHeight(inImageRef1);   //
    
    unsigned char *imgPixel2 = RequestImagePixelData(image2);   //√ä‚â•¬Æ√ä√ë√®√Å¬±¬™√Ç√ª√?
	CGImageRef inImageRef2 = [image2 CGImage];
	GLuint w2 = CGImageGetWidth(inImageRef2);   //440
	GLuint h2 = CGImageGetHeight(inImageRef2);  //
    
    
    int newW = MAX(w1, w2);
    int newH = MAX(h1, h2); 
    int length = newH * newW * 4;
    unsigned char *newImagePixel = (unsigned char *)calloc(length, sizeof(unsigned char));
    int y1, y2, x1, x2;

            
    long startByte1 = 0;
    long startByte2 = 0;
    long startByte = 0;
    
    int m = 2;
    for(GLuint y = 0;y < newH/m;y++)
	{
		for (GLuint x = 0; x<newW; x++)
		{
            y1 = y * h1 / newH * m;
            x1 = x * w1 / newW;
            
            startByte = (y * newW +x) * 4;
            startByte1 = (y1 * w1 + x1) * 4;
            
            newImagePixel[startByte] = imgPixel1[startByte1];
            newImagePixel[startByte+1] = imgPixel1[startByte1+1];
            newImagePixel[startByte+2] = imgPixel1[startByte1+2];
            newImagePixel[startByte+3] = imgPixel1[startByte1+3];
        }
    }
    
    
    for(GLuint y = newH/2;y< newH;y++)
	{
		for (GLuint x = 0; x<newW; x++)
		{
            y2 = (y-newH/2) * h2 / newH * m;
            x2 = x * w2 / newW;
            
            startByte = (y * newW +x) * 4;
            startByte2 = (y2 * w2 + x2) * 4;

            newImagePixel[startByte] = imgPixel2[startByte2];
            newImagePixel[startByte+1] = imgPixel2[startByte2+1];
            newImagePixel[startByte+2] = imgPixel2[startByte2+2];
            newImagePixel[startByte+3] = imgPixel2[startByte2+3];
        }
    }
    
    
    UIImage *newImage = [QImage createNewImageByImagePixel:newImagePixel width:newW height:newH];
    return newImage;
}

//+ (UIImage)scaleToSize:(CGSize)size{
//    UIgr
//}

+ (UIImage *)scaleImage:(UIImage *)image ToWidth:(int)newW Height:(int)newH{
    unsigned char *imagePixel = RequestImagePixelData(image);
	CGImageRef imageRef = [image CGImage];
	GLuint w = CGImageGetWidth(imageRef);
	GLuint h = CGImageGetHeight(imageRef);
    long startByte = 0;
    
    int length = newH * newW * 4;
    unsigned char *newImagePixel = (unsigned char *)calloc(length, sizeof(unsigned char));
    
    int newY, newX;
    long newStartByte;
    
    for(int y = 0;y < h;y++)
	{
		for (int x = 0; x < w; x++)
		{
            newY = y * newH / h;
            newX = x * newW / w;
            
            startByte = (y * w +x) * 4;
            newStartByte = (newY * newW + newX) * 4;
            
            newImagePixel[newStartByte] = imagePixel[startByte];
            newImagePixel[newStartByte+1] = imagePixel[startByte+1];
            newImagePixel[newStartByte+2] = imagePixel[startByte+2];
            newImagePixel[newStartByte+3] = imagePixel[startByte+3];
        }
    }
    
    UIImage *newImage = [QImage createNewImageByImagePixel:newImagePixel width:newW height:newH];
    return newImage;
}

+ (UIImage *)scaleImage:(UIImage *)image adjustToTemplet:(UIImage *)templet{
    CGImageRef templetRef = [templet CGImage];
	GLuint w_templet = CGImageGetWidth(templetRef);
	GLuint h_templet = CGImageGetHeight(templetRef);
    
    UIImage *imageTemp = [ImageUtil scaleImage:image ToWidth:w_templet Height:h_templet];
    return imageTemp;
}

+ (UIImage *)LayerMultiplyImage:(UIImage *)image templet:(UIImage *)templet{
//    UIImage *imageTemp = [ImageUtil scaleImage:image adjustToTemplet:templet];
//    unsigned char *imagePixel = RequestImagePixelData(imageTemp);
    unsigned char *imagePixel = RequestImagePixelData(image);
    
    unsigned char *templetPixel = RequestImagePixelData(templet);
    
	CGImageRef templetRef = [templet CGImage];
	GLuint w_templet = CGImageGetWidth(templetRef);
	GLuint h_templet = CGImageGetHeight(templetRef);
    
    unsigned char *newImagePixel = mixedPixel_layerMultiply(imagePixel, templetPixel, w_templet, h_templet);
    
    UIImage *newImage = [QImage createNewImageByImagePixel:newImagePixel width:w_templet height:h_templet];
    return newImage;
}

@end
